package service.impl;

import pojo.Category;
import pojo.vo.BookVo;
import service.CategoryService;
import libaryinterface.interfaceutils.MyDialogDemo;
import mapper.BookMapper;
import mapper.BookRecordMapper;
import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import pojo.Book;
import pojo.BookRecord;
import pojo.User;
import pojo.vo.BookRecordVo;
import service.BookRecordService;
import service.UserService;
import utils.GetSqlSession;
import utils.TimeFormat;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-12-06
 * Time: 17:34
 */
public class BookRecordServiceImpl implements BookRecordService {
    SqlSession sqlSession = GetSqlSession.getSqlSession();
    BookRecordMapper bookRecordMapper = sqlSession.getMapper(BookRecordMapper.class);

    BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    CategoryService categoryService = new CategoryServiceImpl();
    /**
     * 用户借书
     * @param bookId 书的id
     * @param userId  用户账号
     * @param loanDay 借阅天数
     * @param loanNumber 借阅数量
     * @return
     */
    @Override
    public boolean LendBook(Long bookId, String userId, Long loanDay, Long loanNumber) {
        //先判断借阅数量是否大于剩余数量
        List<BookVo> books = bookMapper.listBookByBookId(bookId);
        BookVo bookVo = books.get(0);
        if(bookVo.getSurplusNumber()<loanNumber){
            return false;
        }

        //借阅时间为当前时间(转换时间格式）
        LocalDate lendTime = TimeFormat.timeFormat();
        //计算归还日期
        LocalDate returnTime = lendTime.with(temporal -> temporal.plus(loanDay, ChronoUnit.DAYS));

        //创建一个新的记录对象并为其赋值
        BookRecord bookRecord = new BookRecord();
        bookRecord.setBookId(bookId);
        bookRecord.setUserId(userId);
        bookRecord.setLendTime(lendTime);
        bookRecord.setReturnTime(returnTime);
        bookRecord.setLoanLength(loanDay);
        bookRecord.setIsOverdue("否");
        bookRecord.setFineMoney(0);
        bookRecord.setLoanNumber(loanNumber);
        bookRecord.setState("否");

        //插入数据库
        boolean flag = bookRecordMapper.addBookRecord(bookRecord);
        //更新书籍的剩余数量 和 借出数量
        if(flag){
            Book book = bookMapper.getBookByName( bookVo.getName());
            //当前借的书剩余数量-loanNumber，
            book.setSurplusNumber(book.getSurplusNumber()-loanNumber);
            //当前借的书借出数量+loanNumber，
            book.setLendNumber(book.getLendNumber()+loanNumber);
            //将修改更新到数据库
            bookMapper.modifyBook(book,bookId);
        }

        //更新用户已经借书的数量
        //先根据用户id获取到当前用户
        User user = userMapper.getUserByAccount(userId);
        //修改该已经借阅的数量
        user.setAlreadyNumber( user.getAlreadyNumber() + loanNumber);
        //调用用户修改方法,将更新到数据库
        boolean flag2 = userMapper.modifyUser(user);
        if( flag2){
            return true;
        }
        return false;
    }

    /**
     * 添加借阅记录
     * @param bookName 书的名称
     * @param userName  用户姓名
     * @param loanDay 借阅天数
     * @param loanNumber 借阅数量
     * @return
     */
    @Override
    public boolean addBookRecord(String bookName, String userName, Long loanDay, Long loanNumber) {
        //先判断借阅数量是否大于剩余数量
        Book book = bookMapper.getBookByName(bookName);
        if(book == null){
            new MyDialogDemo("要借阅的书籍不存在");
            return false;
        }
        User user = userMapper.getUserByName(userName);      //根据用户id获取到当前用户
        if(user == null ){
            new MyDialogDemo("该用户不存在");
            return false;
        }
        Category category = categoryService.getCategoryByAccount(user.getAccount()); //  根据用户id获取到当前用户身份
        Long MaxLoanNumber = category.getLoanNumber();;//获取当前用户的最大借阅数
        Long MaxLoanDay = category.getLoanTime();//获取当前用户的最大借阅天数

        //借书的条件判断
        if(book.getSurplusNumber()<loanNumber){
            new MyDialogDemo("库存不足");
            return false;
        }

        if(user.getAlreadyNumber()+loanNumber > MaxLoanNumber){
            new MyDialogDemo("该用户的借阅数超过最大借阅数");
            return false;
        }

        if( MaxLoanDay < loanDay){
            new MyDialogDemo("超过最长借阅时间");
            return false;
        }

        //借阅时间为当前时间(转换时间格式）
        LocalDate lendTime = TimeFormat.timeFormat();
        //计算归还日期
        LocalDate returnTime = lendTime.with(temporal -> temporal.plus(loanDay, ChronoUnit.DAYS));

        //创建一个新的记录对象并为其赋值
        BookRecord bookRecord = new BookRecord();
        bookRecord.setBookId(book.getSnid());
        bookRecord.setUserId(user.getAccount());
        bookRecord.setLendTime(lendTime);
        bookRecord.setReturnTime(returnTime);
        bookRecord.setLoanLength(loanDay);
        bookRecord.setIsOverdue("否");
        bookRecord.setFineMoney(0);
        bookRecord.setLoanNumber(loanNumber);
        bookRecord.setState("否");

        //插入数据库并更新书籍的数量
        boolean flag = bookRecordMapper.addBookRecord(bookRecord);
        if(flag){
            //当前借的书剩余数量-loanNumber，
            book.setSurplusNumber(book.getSurplusNumber()-loanNumber);
            //当前借的书借出数量+loanNumber，
            book.setLendNumber(book.getLendNumber()+loanNumber);
            //将修改更新到数据库
            bookMapper.modifyBook(book,book.getSnid());
        }

        //更新用户已经借书的数量
        //修改该用户已经借阅的数量
        user.setAlreadyNumber( user.getAlreadyNumber() + loanNumber);
        //调用用户修改方法,将更新到数据库
        boolean flag2 = userMapper.modifyUser(user);
        if( flag2){
            return true;
        }
        return false;
    }


    /**
     * 删除借阅记录
     * @param recordId 选中记录的id
     * @param bookName 选中书籍的名称
     * @param returnNumber 归还的数量
     * @param account 归还的用户账号
     * @return
     */
    @Override
    public boolean deleteRecord(Long recordId, String bookName, Long returnNumber,String account) {

        //先将借阅人已经借的书的数量-归还的数量
        UserService userService = new UserServiceImpl();
        User user = userService.getUserByAccount(account);
        user.setAlreadyNumber( user.getAlreadyNumber() - returnNumber);
        //更新数据库
        userService.modifyUser(user);

        //删除成功后，更新这本书的剩余和借出数量
        bookRecordMapper.deleteRecord(recordId);

         //当前借的书的剩余数量+归还的数量，
         Book book = bookMapper.getBookByName(bookName);
         book.setSurplusNumber(book.getSurplusNumber()+returnNumber);
         //当前借的书的借出数量-归还的数量，
         book.setLendNumber(book.getLendNumber()-returnNumber);
         //将更新书的借出数量和剩余数量 到数据库
         boolean glag = bookMapper.modifyBook(book,book.getSnid());
        if(glag){
            new MyDialogDemo("归还成功");
            return true;
        }
        return false;
    }


    /**
     * 查看所有借阅记录
     * @return
     */
    @Override
    public List<BookRecordVo> listBookRecord() {
       return bookRecordMapper.listBookRecord();
    }

    /**
     * 根据用户id显示该用户的借阅记录
     * @param account
     * @return
     */
    @Override
    public List<BookRecordVo> listBookRecordByAccount(String account) {
        return bookRecordMapper.listBookRecordByAccount(account);
    }

    /**
     * 修改逾期状态
     * @param recordId
     * @return
     */
    @Override
    public boolean setOverDue(Long recordId) {
        return bookRecordMapper.setOverDue(recordId);
    }

    /**
     * 对过期的借阅记录进行罚款
     * @param fineMoney
     * @param recordId
     * @return
     */
    @Override
    public boolean setFineMoney(Double fineMoney, Long recordId) {
        return bookRecordMapper.setFineMoney(fineMoney,recordId);
    }


    /**
     * 归还借阅记录
     * @param recordId
     * @param bookName
     * @param returnNumber
     * @param account
     * @return
     */
    @Override
    public boolean returnRecord(Long recordId, String bookName, Long returnNumber, String account) {

        //先将借阅人已经借的书的数量-归还的数量
        UserService userService = new UserServiceImpl();
        User user = userService.getUserByAccount(account);
        user.setAlreadyNumber( user.getAlreadyNumber() - returnNumber);

        //更新数据库
        userService.modifyUser(user);
        LocalDate curTime = TimeFormat.timeFormat();

        //修改这条记录的状态
        bookRecordMapper.returnRecord(recordId, curTime);
        //归还成功后，更新这本书的剩余和借出数量
        //当前借的书的剩余数量+归还的数量，
        Book book = bookMapper.getBookByName(bookName);
        book.setSurplusNumber(book.getSurplusNumber()+returnNumber);

        //当前借的书的借出数量-归还的数量，
        book.setLendNumber(book.getLendNumber()-returnNumber);
        //将更新书的借出数量和剩余数量 到数据库
        boolean glag = bookMapper.modifyBook(book, book.getSnid());
        if(glag){
            return true;
        }
        return false;
    }
}
